from ktit.storage.models import Category
from django.utils._threading_local import local


#def recursive_get_category_list(parentid, level, expanded_catid):
def recursive_get_category_list(cat, level, expanded_catid):    
    #cat = Category.objects.select_related().filter(parent=parentid)
    
    res = []

    for ci in cat:
        item = {}  
        item["id"]=ci.id
        item["name"]=ci.name
        item["parent"]=ci.parent
        item["level"]=level
        item["csslevel"]=level * 12
        item["expanded"]=False

        if expanded_catid:
            if item["id"] in expanded_catid:
                item["expanded"]=True    
        else:
            item["expanded"]=True

        #item["child_present"] = Category.objects.select_related().filter(parent=item["id"]).count()
        category_set = ci.category_set.all()
        item["child_present"] = len(category_set)

        res.append(item)

        if(item["expanded"]): 
            #subcategories=recursive_get_category_list(item["id"], level+1, expanded_catid)
            subcategories=recursive_get_category_list(category_set, level+1, expanded_catid)
            res.extend(subcategories)

    return res


def recursive_get_category_list_ex(cat, level, expanded_catid):
    res = []
    for ci in cat:
        item = {"id":ci.id,"name":ci.name,"parent":ci.parent,"level":level,"csslevel":level*12,"expanded":False,}
        if expanded_catid:
            if item["id"] in expanded_catid:
                item["expanded"]=True    
        else:
            item["expanded"]=True
        category_set = ci.category_set.all()
        item["child_present"] = category_set
        res.append(item)
        if(item["expanded"]): 
            subcategories=recursive_get_category_list(category_set, level+1, expanded_catid)
            res.extend(subcategories)
    return res



def create_cat_tree(expanded_catid):
    c = Category.objects.select_related().filter(parent=None)
    #print Category.objects.select_related().all()
    #return recursive_get_category_list(c.id, 0, expanded_catid)
    return recursive_get_category_list_ex(c, 0, expanded_catid)